//
//  CSMACANoVCSListener.cpp
//  WiFiMACSim
//
//  Created by Christopher Kemsley on 4/1/12.
//  Copyright (c) 2012 iAppolopolis. All rights reserved.
//

#include "CSMACAVCSListenerNoVCS.hpp"
#include "Settings.hpp"

using namespace Sim ;



CSMACANoVCSListener :: CSMACANoVCSListener ( ID const & name )
:	TransitionalStateMachineNode<CSMACANoVCSListener> ( name )
,	timer()
	{
	registerStateCallback ( kStateIdle , &CSMACANoVCSListener::update_idle , "Idle. Waiting for RTS" ) ;
	
	registerStateCallback ( kStateSendingAck , &CSMACANoVCSListener::update_xmitAck , "Sending ACK" ) ;
	}











void	CSMACANoVCSListener :: update_idle		( Message * incoming , bool completed , bool isBusy )
	{
	if ( incoming != 0 )
		{
		if ( incoming->target == identity )
			incoming->status = Message::kStatusSuccessful ;
		
		if ( !completed ) return ; // wait for it to complete
		
		switch ( incoming->type )
			{
				case Message::kTypeData : {
					if ( incoming->target == identity )
						{
						sender = incoming->sender ;
						
						setState(kStateSendingAck) ;
						message = new Message ( identity , sender , Message::kTypeACK , Settings::shared().controlPacketDuration ) ;
						Medium::shared().registerMessage(message) ;
						
						break ;
						}
				}
				
				default : {
					//ThrowException ( "CSMACANoVCSListener" , "Should not be receiving any ACK in idle state" , __FILE__,__LINE__ ) ;
				} break ;
			}
		}
	}




void	CSMACANoVCSListener :: update_xmitAck( Message * incoming , bool completed , bool isBusy )
	{
	if ( ! message->isInFlight )
		{
		/* Statistics */
		if ( message -> status != Message::kStatusSuccessful )
			{
			//std::cout << NodeStamp << "ACK Message was never received/handled\n" ;
			}
		/* Statistics */
		
		message -> release() ;
		message = 0 ;
		
		setState ( kStateIdle ) ;
		}
	}

